package com.aliyun.oss.hash;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@SpringBootApplication
public class HashApplication {

    private static final String ALGORITHM = "SHA-256";
    private static final Map<String, List<Path>> hashToFilePaths = new ConcurrentHashMap<>();

    public static void main(String[] args) throws Exception {
        Path startPath = Paths.get("E:\\JavaWeb开发教程资料"); // 修改为你的硬盘路径
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (attrs.isRegularFile()) {
                    String hash = null;
                    try {
                        hash = computeHash(file);
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException(e);
                    }
                    hashToFilePaths.computeIfAbsent(hash, k -> new ArrayList<>()).add(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });

        findDuplicates();
    }

    private static String computeHash(Path file) throws IOException, NoSuchAlgorithmException {
        try (InputStream fis = Files.newInputStream(file)) {
            MessageDigest digest = MessageDigest.getInstance(ALGORITHM);
            byte[] byteArray = new byte[1024];
            int bytesCount;
            while ((bytesCount = fis.read(byteArray)) != -1) {
                digest.update(byteArray, 0, bytesCount);
            }
            byte[] bytes = digest.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        }
    }

    private static void findDuplicates() {
        for (List<Path> paths : hashToFilePaths.values()) {
            if (paths.size() > 1) {
                System.out.println("Duplicate files found:");
                for (Path path : paths) {
                    System.out.println(path);
                }
            }
        }
    }
    }